﻿using HalconDotNet;
using LD.BC;
using LD.Host;
using LD.Mes.Sharp;
using LD.Mes;
using LD.Tool;
using LD.项目;
using PubSub;
using ReaLTaiizor.Util;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using LD.Host.WIP;

namespace LD.Tool
{
    [Tool(Text = "FOBAOI检测", FrmParam = "ToolFobAoiFrm", ToolType = ToolEnum.项目)]
    public class ToolFobAoi : BaseTool
    {
        private TB_Tool _tool;
        private double offset_x;
        private double offset_y;
        private double offset_r;
        private double max;
        private double min;
        private string barcode;
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                _tool = model;
                stopwatch.Start();
                if (model.Param != null)
                {
                    offset_x = (double)Cache.GetCache(CONST.FOBAOI_OFFSET_X);
                    offset_y = (double)Cache.GetCache(CONST.FOBAOI_OFFSET_Y);
                    offset_r = (double)Cache.GetCache(CONST.FOBAOI_OFFSET_R);
                    var barcodeModel = Cache.Var.Where(p => p.Name == "").FirstOrDefault();
                    if (barcodeModel != null)
                        barcode = barcodeModel.ToString();
                    else
                        Log(model, "无条码信息", LogLevel.警告);
                    var param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolFobAoiParam>(model.Param);
                    //keyence change workmodel
                    string res = CommunicateFactory.Instance.TcpIp[param.TcpIpName].Send("R0\r", 1000);

                    //get testpoint
                    var testPoint = (List<FobAoiTestPoint>)Cache.GetCache(Appbus.PartNo.CurrentPartNo + "_");
                    if (testPoint != null && testPoint.Count > 0)
                    {
                        //get axis id
                        var axisId = Appbus.PartNo.Config.AxisPoint
                                        .Where(p => p.Name == "检测点")
                                        .FirstOrDefault();
                        if (axisId != null)
                        {
                            int index = 1;
                            StringBuilder sb = new StringBuilder();
                            foreach (var item in testPoint)
                            {
                                //判定是否暂停了
                                LightStopHelper.Instance.PauseWait();

                                Log(model, $"定位到[{index}段]起始", LogLevel.一般);
                                MoveTestPoint(axisId, item);
                                sb.Append(TestByMoveByDy(param, item));
                                index++;
                            }
                            SaveDB(sb.ToString());
                        }
                    }
                }
                if (!isSuccess)
                    Log(model, $"测试失败", LogLevel.警告);
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
        private void SaveDB(string testData)
        {
            string pass_ng = ParseTestData(testData);
            if (pass_ng.Equals("NG"))
            {
                Appbus.Wip.SetWip(ResultType.NG);
            }
            else
            {
                Appbus.Wip.SetWip(ResultType.OK);
            }
            //本地存档
            DBHelper.Instance.Sql.Insertable(new TB_FobAoi()
            {
                SN = barcode,
                Result = pass_ng,
                TestData = testData,
                PartNo = Appbus.PartNo.CurrentPartNo,
                Max = max,
                Min = min
            }).ExecuteCommand();
            //上传mes
            if ((bool)Cache.GetCache(CONST.DPT_ISMES))
            {

            }
        }
        public string ParseTestData(string testData)
        {
            if (testData.IndexOf(",1") > 0)
            {
                return "NG";
            }
            else
            {
                return "OK";
            }
        }
        private void MoveTestPoint(TB_Point axisId, FobAoiTestPoint point)
        {
            var x = axisId.AxisPointDic.Where(p => p.Key == AxisType.X.ToString()).FirstOrDefault();
            var y = axisId.AxisPointDic.Where(p => p.Key == AxisType.Y.ToString()).FirstOrDefault();
            var z = axisId.AxisPointDic.Where(p => p.Key == AxisType.Z.ToString()).FirstOrDefault();
            var r = axisId.AxisPointDic.Where(p => p.Key == AxisType.R.ToString()).FirstOrDefault();
            BcFactory.Instance.Control.Move_Location(x.Value.AxisId, point.StartPoint_X + offset_x);
            BcFactory.Instance.Control.Move_Location(y.Value.AxisId, point.StartPoint_Y + offset_y);
            BcFactory.Instance.Control.Move_Location(r.Value.AxisId, point.StartPoint_R + offset_r);
            BcFactory.Instance.Control.Move_Location(z.Value.AxisId, point.StartPoint_Z);
            BcFactory.Instance.Control.WaitAxisComplete();
        }
        /// <summary>
        /// 动态移动
        /// </summary>
        /// <param name="aName"></param>
        /// <returns></returns>
        private string TestByMoveByDy(ToolFobAoiParam param, FobAoiTestPoint point)
        {
            StringBuilder sb = new StringBuilder();
            ushort axis1 = 0;
            double removeVal = (double)Cache.GetCache(CONST.FOBAOI_TESTMOVE);

            int index = 0;
            //test
            string testVal = CommunicateFactory.Instance.TcpIp[param.TcpIpName].Send("TG\r", 1000);

            sb.Append(testVal);
            //get max min
            ParseData(testVal);

            //get move dir
            double mbLocation = 0;
            if (point.StartPoint_X == point.EndPoint_X)
            {
                var x_axis = BcFactory.Instance.Config.AxisParam
                                .Where(p => p.Name.Contains("X"))
                                .FirstOrDefault();
                if (x_axis != null)
                    axis1 = x_axis.AxisId;
                mbLocation = point.EndPoint_Y + offset_x;
            }
            else
            {
                var y_axis = BcFactory.Instance.Config.AxisParam
                                .Where(p => p.Name.Contains("Y"))
                                .FirstOrDefault();
                if (y_axis != null)
                    axis1 = y_axis.AxisId;
                mbLocation = point.EndPoint_X + offset_y;
            }

            //move axis
            double curLocation = BcFactory.Instance.Control.GetAxisPosition(axis1);
            while (curLocation < mbLocation && removeVal > 0)
            {
                //判定是否暂停了
                LightStopHelper.Instance.PauseWait();

                index++;
                //计算移动距离
                curLocation = BcFactory.Instance.Control.GetAxisPosition(axis1);
                if ((mbLocation - curLocation) < removeVal)
                    removeVal = Math.Round(mbLocation - curLocation, 2);

                if (removeVal > 0)
                {
                    Log(_tool, $"移动距离:{removeVal}", LogLevel.一般);
                    //正方向运动
                    BcFactory.Instance.Control.Move_Ration(axis1, 1, removeVal);
                    BcFactory.Instance.Control.WaitAxisComplete();
                    //test
                    testVal = CommunicateFactory.Instance.TcpIp[param.TcpIpName].Send("TG\r", 1000);

                    sb.Append(testVal);
                    //get max min
                    ParseData(testVal);

                    //暂停，后续增加

                }
            }

            return sb.ToString();
        }
        private void ParseData(string data)
        {
            max = (double)Cache.GetCache(CONST.FOBAOI_TESTMIN);
            min = (double)Cache.GetCache(CONST.FOBAOI_TESTMIN);
            List<double> list = new List<double>();
            string regexStr = @"\+\d*.\d*,";   // ""匹配double类型"
            MatchCollection matchs = Regex.Matches(data, regexStr);
            foreach (var item in matchs)
            {
                int dd = item.ToString().Length - 2;
                list.Add(Convert.ToDouble(item.ToString().Substring(1, dd)));
            }
            if (list.Max() > max)
                max = list.Max();
            if (list.Min() < min)
                min = list.Min();
        }
    }
}
